import type { AxiosRequestConfig } from "@/utils/request";
import type { BaseQueryFn } from "@reduxjs/toolkit/query/react";
import { createApi, retry } from "@reduxjs/toolkit/query/react";
import { request, cancelToken, sourceToken } from "@/utils/request";

export { cancelToken, sourceToken };

const fetchBaseQuery: BaseQueryFn<string | AxiosRequestConfig> = async (args) => {
  const argsInterceptor: AxiosRequestConfig =
    typeof args === "string" ? { url: args, method: "GET" } : { ...args };
  const { url, method = "GET", data = {}, params = {}, headers = {}, ...rest } = argsInterceptor;
  const result = await request({ url, method, data, params, headers, ...rest });

  return result;
};

const baseQueryWithRetry = retry(fetchBaseQuery, { maxRetries: 5 }); // 重试机制

export const apiService = createApi({
  reducerPath: "apiService",
  baseQuery: baseQueryWithRetry,
  // 缓存，默认时间是秒，默认时长60秒
  keepUnusedDataFor: 5 * 60,
  refetchOnMountOrArgChange: 30 * 60,
  endpoints: () => ({}),
  tagTypes: [],
});
